package com.ldx.eduline.college.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ldx.eduline.college.entity.EduSubject;
import com.ldx.eduline.college.mapper.EduSubjectMapper;
import com.ldx.eduline.college.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldx.eduline.common.utils.List2Tree;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ldx
 * @since 2020-12-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public List<EduSubject> tree() {
        // 查询所有分类
        List<EduSubject> subjectList = baseMapper.selectList(null);

        // 转为父子结构

        // 1.找到一级分类
        List<EduSubject> rootSubject = subjectList.stream().filter((entity) -> {
            return entity.getParentId() .equals("0");
        }).map((menu)->{
            return menu.setChildren(getChildren(menu,subjectList));
        }).collect(Collectors.toList());

        return rootSubject;
    }

    /**
     * 获取对应的子节点
     * @param rootSubject
     * @param subjectList
     * @return
     */
    public List<EduSubject> getChildren(EduSubject rootSubject,List<EduSubject> subjectList){
        List<EduSubject> list = subjectList.stream().filter(suject -> {
            return suject.getParentId().equals(rootSubject.getId());
        }).map((subject) -> {
            subject.setChildren(getChildren(subject, subjectList));
            return subject;
        }).sorted((s1,s2)->{
            return s1.getSort() - s2.getSort();
        }).collect(Collectors.toList());
        return list;
    }

}
